package com.example.test2.main.fragment;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.test2.R;
import com.example.test2.activity.MsgActivity;
import com.example.test2.databinding.FragmentMsgBinding;
import com.example.test2.db.control.UserDbController;
import com.example.test2.db.entity.User;
import com.example.test2.event.MsgEvent;
import com.example.test2.http.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


public class MsgFragment extends BaseFragment<FragmentMsgBinding> {

    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        update();
    }

    private void update() {
        User user = UserDbController.getInstance(getActivity()).searchByName(Constants.PHONE);
        if (null== user)
            return;
        List<String> list = user.getMsgList();
        String date= user.getDate();
        getBinding().tvMsg.setText(list.get(list.size()-1));
        getBinding().tvTime.setText(date);
    }

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().rlChat.setOnClickListener(view -> {
            startActivity(new Intent(getActivity(), MsgActivity.class));
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_msg;
    }

    @Override
    protected FragmentMsgBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent) {
        return FragmentMsgBinding.inflate(inflater, parent, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MsgEvent event) {
        update();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    };
